package com.unittec.zk.provider.scope;

import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.springframework.cloud.context.scope.ScopeCache;

/**
 * @author wuxinwei
 */
public class ThreadLocalScopeCache implements ScopeCache {
    private final ThreadLocal<ConcurrentMap<String, Object>> data = new ThreadLocal<ConcurrentMap<String, Object>>() {
        @Override
        protected ConcurrentMap<String, Object> initialValue() {
            return new ConcurrentHashMap<String, Object>();
        }
    };

    public ConcurrentMap<String, Object> getThread() {
        return data.get();
    }


    public  void removeAll(){
        if(data.get()!=null){
            data.get().clear();
        }
    }

    @Override
    public Object remove(String name) {
        return data.get().remove(name);
    }

    @Override
    public Collection<Object> clear() {
        ConcurrentMap<String, Object> map = data.get();
        Collection<Object> values = new ArrayList<Object>(map.values());
        map.clear();
        return values;
    }

    @Override
    public Object get(String name) {
        return data.get().get(name);
    }

    @Override
    public Object put(String name, Object value) {
        Object result = data.get().put(name, value);
        if (result != null) {
            return result;
        }
        return value;
    }

}
